/*
 * @Author: GuitarXiaohe && 2205227953@qq.com
 * @Date: 2024-01-17 21:22:34
 * @LastEditors: 18163104359 2205227953@qq.com
 * @LastEditTime: 2024-01-23 18:16:03
 * @FilePath: /umi/src/models/appConfig.ts
 * @Description: 菜单数据汇总
 * QQ:2205227953,邮箱:2205227953@qq.com
 * Copyright (c) 2024 by GuitarXiaohe, All Rights Reserved.
 */
import { getToken } from "@/utils/auth";
import { GetRoutersAPI } from "@/api/common";
import { history } from "umi";
import fullLoading from "@/utils/loading";
import XHicon from "@/components/xh-components/xh-icon/index.jsx";
import { dynamicRoutes } from "../../config/routes/index";
import defaultConfig from "../../appConfig.ts";
const appConfig = {
  namespace: "appConfig",
  state: {
    size: "Middle", // 组件大小
    siderMenuTheme: "dark", // 侧边栏颜色 （dark）
    theme: "dark", // 白天或者黑夜主题色
    colorPrimary: "#2883fb", // 组件主体色
    watermark: null, // 水印
    menuOpenKey: "", // 当前菜单目录选中
    menuKey: "", // 当前菜单选中
    navigationKey: "", //
    menuList: [], // 菜单数据
    navigationMenu: [], // 底部导航
    siderMenu: [], // 侧边导航
    breadcrumb: [], // 面包屑
    collapsed: false, // 侧边栏状态
    navigation: "1", // 是否底部导航
    spinning: false, //全局加载中
  },
  effects: {
    // 1 为顶部导航 2 为侧边栏导航
    *getMenuList({ payload }, { call, put, select }) {
      const appConfigObj = JSON.parse(sessionStorage.getItem("appConfig"));
      if (!getToken()) return;
      const { data: result } = yield call(() => GetRoutersAPI());
      yield put({
        // 请求完事之后的调用的reducers方法
        type: "menuAndNavigation",
        payload: {
          menuList: result,
          menuType: payload
            ? payload
            : appConfigObj
            ? appConfigObj.navigation
            : defaultConfig.APP_SETTING_NAVIGATION,
        },
      });
    },
  },
  reducers: {
    // 初始化配置
    initAppConfig(state, { payload }) {
      // 本地保存key使用变量名代替 等待修改
      const appConfigObj = JSON.parse(sessionStorage.getItem("appConfig"));
      console.log(appConfigObj);
      if (appConfigObj != null) {
        return {
          ...state,
          size: appConfigObj.size || defaultConfig.APP_SETTING_SIZE,
          siderMenuTheme: appConfigObj.siderMenuTheme || defaultConfig.APP_SETTING_SIDER_THEME,
          theme: appConfigObj.theme || defaultConfig.APP_SETTING_THEME,
          colorPrimary: appConfigObj.colorPrimary || defaultConfig.APP_SETTING_COLOR_PRIMARY,
          navigation: appConfigObj.navigation || defaultConfig.APP_SETTING_NAVIGATION,
          watermark: appConfigObj.watermark || defaultConfig.APP_SETTING_WATERMARK,
        };
      } else {
        return {
          ...state,
          size: defaultConfig.APP_SETTING_SIZE,
          siderMenuTheme: defaultConfig.APP_SETTING_SIDER_THEME,
          theme: defaultConfig.APP_SETTING_THEME,
          colorPrimary: defaultConfig.APP_SETTING_COLOR_PRIMARY,
          navigation: defaultConfig.APP_SETTING_NAVIGATION,
          watermark: defaultConfig.APP_SETTING_WATERMARK,
        };
      }
    },
    // 赋值组件主体色
    setColorPrimary(state, { payload: theme }) {
      const r = { ...state, colorPrimary: theme };
      // sessionStorage.setItem("appConfig", JSON.stringify(r));
      return r;
    },
    // 赋值全局主体色
    setTheme(state, { payload: theme }) {
      const r = { ...state, theme };
      // sessionStorage.setItem("appConfig", JSON.stringify(r));
      return r;
    },
    // 赋值侧边栏颜色
    setSiderMenuTheme(state, { payload: theme }) {
      const r = { ...state, siderMenuTheme: theme };
      // sessionStorage.setItem("appConfig", JSON.stringify(r));
      return r;
    },
    // 赋值是否底部导航
    setNavigation(state, { payload: val }) {
      const r = { ...state, navigation: val };
      // sessionStorage.setItem("appConfig", JSON.stringify(r));
      return r;
    },

    // 赋值水印
    setWatermark(state, { payload: val }) {
      const r = { ...state, watermark: val };
      // sessionStorage.setItem("appConfig", JSON.stringify(r));
      return r;
    },

    // 本地保存
    sunitConfig(state, { payload: val }) {
      const r = {
        size: state.size, // 组件大小
        siderMenuTheme: state.siderMenuTheme, // 侧边栏颜色 （dark）
        theme: state.theme, // 白天或者黑夜主题色
        colorPrimary: state.colorPrimary, // 组件主体色
        navigation: state.navigation, // 是否底部导航
        watermark: state.watermark, // 水印
      };
      sessionStorage.setItem("appConfig", JSON.stringify(r));
      return { ...state, ...r };
    },
    // 顶部导航与侧边栏导航处理   1 为顶部导航 2 为侧边栏导航
    menuAndNavigation(state, { payload, put }) {
      let r = {
        label: "首页",
        path: "/index",
        key: "/index",
        icon: <XHicon icon={"home"} />,
      };
      const defaultData = JSON.parse(JSON.stringify(payload.menuList));
      const defaultRoutes = filterAsyncRouter(defaultData, false, true);
      let navigationMenu = [],
        siderMenu = [],
        collapsed = false,
        navigationKey = "";
      // 1 为顶部导航
      if (payload.menuType == "1") {
        navigationMenu = [r, ...defaultRoutes];

        const rootKey = history.location.pathname.split("/");
        // dispatch({
        //   type: "appConfig/setCollapsed",
        //   payload: val.key == "/index",
        // });

        if (rootKey.length > 2) {
          navigationKey = "/" + rootKey[1];
          const route = defaultRoutes.find((item) => item.path === "/" + rootKey[1]);
          if (route && route.children) {
            siderMenu = [r, ...route.children];
          }
        }

        if (rootKey[1] == "index") {
          collapsed = true;
          navigationKey = "/index";
        }
      }
      // 2 为侧边栏导航
      if (payload.menuType == "2") {
        siderMenu = [r, ...defaultRoutes];
      }

      return {
        ...state,
        menuList: defaultRoutes,
        siderMenu,
        navigationMenu,
        collapsed,
        navigationKey,
      };
    },
    // 赋值当前菜单目录选中数据 弃用掉了
    setMenuOpenKey(state, { payload: menuOpenKey }) {
      return { ...state, menuOpenKey: menuOpenKey };
    },
    // 赋值当前菜单选中数据
    setMenuKey(state, { payload: menuKey }) {
      return { ...state, menuKey };
    },
    // 赋值给侧边栏菜单数据
    setSiderMenu(state, { payload }) {
      let r = {
        label: "首页",
        path: "/index",
        key: "/index",
        icon: <XHicon icon={"home"} />,
      };

      return { ...state, siderMenu: [r, ...payload] };
    },
    // 赋值给底部菜单数据
    setNavigationMenu(state, { payload: menuList }) {
      return { ...state, navigationMenu: menuList };
    },

    // 赋值侧边栏
    setCollapsed(state, { payload }) {
      return { ...state, collapsed: payload };
    },

    // 顶部导航选中
    setNavigationKey(state, { payload }) {
      return { ...state, navigationKey: payload };
    },
    // 全局加载
    loading(state, { payload }) {
      fullLoading.show();
      return { ...state, spinning: true };
    },
    // 关闭全局加载
    closeLoading(state, { payload }) {
      fullLoading.hide();
      return { ...state, spinning: false };
    },
  },

  // 订阅 一开始就会被执行
  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由变化 根据页面地址 触发指定的函数（每次切换路由都会被触发）
      return history.listen(({ pathname }) => {
        // 调用 effects 对象里的异步函数体
        if (pathname) {
          console.log("执行init");
        }
      });
    },
  },
};

export default appConfig;

function filterAsyncRouter(asyncRouterMap, lastRouter, type = false) {
  let r = [];
  asyncRouterMap.forEach((route, ind) => {
    let data = {};

    data.label = route.meta ? (route.meta.title ? route.meta.title : "") : "";
    data.path = route.menuType != "M" ? `/${route.path}` : route.path;
    data.key = route.path.includes("/") ? route.path : "/" + route.path;
    data.icon = route.meta ? (route.meta.icon ? route.meta.icon : "") : "";
    data.activeMenu = route.activeMenu;
    if (type && route.children && route.menuType == "M") {
      data.children = filterChildren(route.children, data);
    }

    // data.icon = <UpOutlined></UpOutlined>;
    if (route.children && route.children.length > 0 && route.menuType == "M") {
      data.children = filterAsyncRouter(route.children, route, type);
    }

    if (route.menuType == "C" && Array.isArray(route.children)) {
      data = {
        label: route.children[0].meta.title,
        path: route.children[0].path,
        key: route.children[0].path,
        icon: route.children[0].meta.icon,
        children: false,
      };
    }
    // 隐藏菜单
    if (!route.hidden) {
      r.push({
        label: data.label,
        path: data.path,
        key: data.key,
        icon: data.icon ? <XHicon icon={data.icon} /> : "",
        children: data.children,
      });
    }
  });

  return r;
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    el.icon = el.icon ? <XHicon icon={el.icon} /> : false;
    if (el.children && el.children.length) {
      el.children.forEach((c) => {
        if (el.menuType == "C" && el.component == "Layout") {
          c.path = c.path;
        } else {
          c.path = el.path + "/" + c.path;
        }
        if (c.children && c.children.length) {
          children = children.concat(filterChildren(c.children, c));
        }
        children.push({
          label: c.name,
          key: c.path,
          path: c.path,
          icon: c.icon ? <XHicon icon={c.icon} /> : false,
        });
      });
      return;
    }

    if (lastRouter) {
      if (el.menuType == "C" && el.component == "Layout") {
        el.path = el.path;
      } else {
        el.path = lastRouter.path + "/" + el.path;
      }
    }
    children = children.concat([
      {
        label: el.name,
        key: el.path,
        path: el.path,
        icon: el.icon ? <XHicon icon={el.icon} /> : false,
      },
    ]);
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  ret;
};
